package com.mms.controller.admin;

import com.mms.context.Constants;
import com.mms.entity.model.Loginform;
import com.mms.pojo.SysManager;
import com.mms.pojo.SysMenu;
import com.mms.pojo.SysOperate;
import com.mms.pojo.SysRoleOperate;
import com.mms.service.SysMenuService;
import com.mms.service.SysOperateService;
import com.mms.utils.CookieUtils;
import com.mms.utils.RequestUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by dangz on 2017/5/21/021.
 */
@Controller
public class WelController extends BaseController {

    private Logger logger = Logger.getLogger(WelController.class);

    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysOperateService sysOperateService;

    @RequestMapping("login")
    public String login(HttpServletRequest request, ModelMap model){
        model.addAttribute("form",new Loginform());
        return "logins";
    }

    @RequestMapping("main")
    public String main(HttpServletRequest request, ModelMap model){
        SysManager account = (SysManager) request.getAttribute(Constants.USER_IN_REQUEST);
        List<SysMenu> menus = null;
        List list = new ArrayList();
        List lists = null;
        Query query = null;
        menus = menuService.getChildMenuInPermissionByRole(null, account.getSysRole().getCode());
        logger.info(account.getSysRole().getCode());
        Map map = null;
        int i = 0;
        String url = "";
        for (SysMenu m : menus) {
            map = new HashMap();
            map.put("menu",m);
            map.put("count",0);

            query = menuService.createSQLQuery("SELECT a.*, b.name as name,c.MENU as cmenu FROM sys_role_operate  a LEFT JOIN sys_menu b on a.MENU=b.ID LEFT JOIN sys_operate c on a.OP=c.OP WHERE a.ROLE='"+account.getSysRole().getCode()+"'"+
                    "and c.OP='list' AND b.status=1 AND b.PID="+m.getId()+" GROUP BY b.ID ").setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
            lists = query.list();
            System.out.println(lists.size());
            if ( lists != null && lists.size() > 0 ){
                map.put("count",1);
                map.put("childs",lists);
                if ( i == 0 ) url = "operate?pid="+((Map)lists.get(0)).get("MENU");
            }else{
                if ( i == 0 ) url = "operate?pid="+m.getId();
            }
            list.add(map);
            i++;
        }
        model.addAttribute("menus", list);
        model.addAttribute("URL2", url);
        return "tmain";
    }

    /**
     * @param pid 父菜单id
     * @param op 操作代码
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "operate")
    public String operate(Long pid,@RequestParam(defaultValue = "list") String op,HttpServletRequest request, HttpServletResponse response,ModelMap model) {
        SysRoleOperate operateId = new SysRoleOperate(pid, op);
        SysOperate operate = sysOperateService.get(operateId);
        if (operate == null) {
            return noright();
        }
        SysManager account = (SysManager) request.getAttribute(Constants.USER_IN_REQUEST);
        if (!sysOperateService.checkPermission(operateId, account.getId())) {
            return noright();
        }

        //正则匹配请求url
        StringBuffer requrl = request.getRequestURL();

        model.addAttribute(Constants.OP_IN_REQUEST, operate);
        SysMenu menu = operate.getSysMenu();
        if ("list".equals(op)) {
            Collection<SysOperate> operates = null;

            //分销商分等级取权限
            if (sysOperateService.checkPermission(operateId, account.getId())) {
                operates = sysOperateService.getOperatesInPermissionByMenu(menu.getId(), account.getId());
            } else {
                return noright();
            }
            model.addAttribute("operates", operates);
            String redirectURL = request.getRequestURI() + "?" + RequestUtils.getQueryString(request);
            try {
                redirectURL = URLEncoder.encode(redirectURL, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            CookieUtils.addCookie(request, response, "_LAST_URL_", redirectURL,null);
        }
        model.addAllAttributes(RequestUtils.getRequestMap(request));
        Map map = RequestUtils.parseQueryString(menu.getParam());
        model.addAllAttributes(map);
        String url = operate.getUrl();

        if (url.startsWith("forward:") || url.startsWith("redirect:")) {
            url = url + (menu.getParam() == null ? "" : "?" + menu.getParam());
            System.out.println(url + (menu.getParam() == null ? "" : "?" + menu.getParam()));
        }

        logger.info(url);
        return url;
    }

    @RequestMapping(value = "noright")
    public String noright(HttpServletRequest request,
                          HttpServletResponse response, ModelMap model) {
        model.addAllAttributes(RequestUtils.getRequestMap(request));
        return "noright";
    }
}